<template>
  <div class="header">
    <div class="logo"><img src="@/assets/images/logo.png" alt="" /></div>
    <el-menu ref="menu" class="el-menu-demo" mode="horizontal" @select="handleSelect" background-color="#161515" text-color="#fff" active-text-color="#e2e537"  router>
      <el-menu-item index="/home">首页</el-menu-item>
      <el-menu-item index="/identify">进入窃漏电识别</el-menu-item>
      <el-menu-item index="/record">窃漏电识别记录</el-menu-item>
    </el-menu>
    <div class="name">窃漏电用户自动识别系统</div>
    <div class="header-right" @click="loginForm" v-show="showlogin" style="margin: 18px 0px">登录/注册</div>
    <el-dialog class="dialog" title="账号登录" :visible.sync="loginFormVisible" width="29%">
      <el-tabs :stretch="true">
        <el-form :model="user" :rules="rules" ref="userForm">
          <el-form-item prop="username">
            <el-input placeholder="请输入账号" size="medium" class="input" prefix-icon="el-icon-user" v-model="user.username"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" size="medium" class="input" prefix-icon="el-icon-lock" show-password v-model="user.password"></el-input>
          </el-form-item>
        </el-form>
      </el-tabs>
      <div>
        <el-checkbox v-model="check" class="rememberMe">记住我</el-checkbox>
        <div class="register">
          <span>没有账号？</span>
          <span class="registerJmp" @click="registerJmp">免费注册</span>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn" type="primary" size="medium" @click="login">登录</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新用户注册" :visible.sync="registerFormVisible" width="29%">
      <el-form :model="registerUser" :rules="registerRules" ref="RuserForm">
        <el-form-item prop="username">
          <el-input placeholder="请输入账号" size="medium" style="margin: 5px 0" prefix-icon="el-icon-user" v-model="registerUser.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" size="medium" style="margin: 5px 0" prefix-icon="el-icon-lock" show-password v-model="registerUser.password"></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input placeholder="请确认密码" size="medium" style="margin: 5px 0" prefix-icon="el-icon-lock" show-password v-model="registerUser.repassword"></el-input>
        </el-form-item>
        <el-form-item> </el-form-item>
      </el-form>
      <div class="register">
        <span>已有账号？</span>
        <span class="registerJmp" @click="loginBack">立即登录</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button class="btn" type="primary" size="medium" @click="register">注册</el-button>
      </div>
    </el-dialog>
     <!-- 用户标签 -->
    <el-dropdown class="userrtag" v-show="showimg">
      <div style="display: inline-block">
        <img :src="img" alt="" style="width: 30px; border-radius: 50%; position: relative; top: 10px; right: 5px" />
        <span style="color: #fff">{{ name }}</span
        ><i class="el-icon-arrow-down" style="margin-left: 5px"></i>
      </div>
      <el-dropdown-menu slot="dropdown" style="width: 100px; text-align: center">
        <el-dropdown-item style="font-size: 14px; padding: 5px 0">
          <router-link to="/Person" class="link">个人信息</router-link>
        </el-dropdown-item>
        <el-dropdown-item style="font-size: 14px; padding: 5px 0">
          <router-link to="/Password" class="link">修改密码</router-link>
        </el-dropdown-item>
        <el-dropdown-item style="font-size: 14px; padding: 5px 0">
          <span style="text-decoration: none" @click="logout">退出</span>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
export default {
  data () {
    return {
    name:'',
    remember:'',//用来实现记住密码
    img:'',
    showlogin: true,//登录标签的显示变量
    showimg:false,//用户标签的显示变量
    loginFormVisible: false, //登录对话框的显示变量
    check: false,
    registerFormVisible: false,
    user: {
        username: '',
        password: '',
      },      //登录用户表单绑定的数据模型对象
      registerUser: {
        username: '',
        password: '',
        repassword: '',
      },
    rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }, 
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
      },   //登录用户的表单绑定的校验规则
      registerRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
        repassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    let haslogin = sessionStorage.getItem('islogin') ? JSON.parse(sessionStorage.getItem('islogin')) : {}; 
    //每次刷新渲染html时判断是否登录过，即获取登录字段，若能获取到则解析成JSON格式再做判断否则为空
    if (haslogin==true) {///如果登录过就根据登录之后后端返回并且保存在本地的DTO数据（user字段）中的username获取用户所有数据并且显示在对应位置
      this.getUser();
    }
    else{
      this.showimg = false;
      this.showlogin = true;
    }
    console.log("页面刷新")
  },
   methods:{
    
    getUser() {
      //先获取本地存储中的当前用户的用户名，然后根据该用户名获取用户数据
      let username = sessionStorage.getItem('user') ? JSON.parse(sessionStorage.getItem('user')).username : '';
      //  获取后台User数据
      this.request.get('/user/username/' + username).then((res) => {
        //  重新赋值后台的最新User数据
        console.log(res)
        let form = res.data.data;
        this.img = form.avatar;
        this.name = form.nickname;
        this.showlogin = false;
        this.showimg = true;
      });
    },
    handleSelect(item) {
      console.log(item);
    },
    loginForm() {
      //每次把登录框打开的时候都检测是否有记住密码的本地存储
      this.loginFormVisible = true;
      this.remember= sessionStorage.getItem('rememberPassword') ? JSON.parse(sessionStorage.getItem('rememberPassword')) : {};
      if(this.remember){
        this.user.username =this.remember.username;
      this.user.password =this.remember.password;
      }
    },
    registerJmp() {
      this.user.username = '';
      this.user.password = '';
      this.loginFormVisible = false;
      this.registerFormVisible = true;
    },
    login() {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          //表单校验合法
          this.request.post('/user/login', this.user).then((res) => {
            console.log("登录POST请求后端返回的数据是"+res)
            if (res.data.code === '200') {
              if (this.check === true) {//登录成功之后检测是否勾选记住密码
         sessionStorage.setItem('rememberPassword', JSON.stringify(res.data.data));//如果勾选了那么把后端返回的DTO中的账号密码保存在本地中
              }
              else{//如果没有勾选则应该清除记住密码存储
            sessionStorage.removeItem('rememberPassword')
              }
              sessionStorage.setItem('user', JSON.stringify(res.data.data)); 
              // 存储用户基本信息到本地存储
              sessionStorage.setItem('islogin',true);//类token机制，登录成功之后设置一个标志/令牌存在本地，方便登录之后放行其他路由
              this.getUser();//获取用户所有数据并显示
              this.loginFormVisible = false;//隐藏登录对话框
           
              this.$message.success('登录成功');
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    loginBack() {
      this.registerFormVisible = false;
      this.loginFormVisible = true;
    },
    register() {
      this.$refs['RuserForm'].validate((valid) => {
        if (valid) {
          //表单校验合法
          if (this.registerUser.password != this.registerUser.repassword) {
            this.$message.error('两次输入的密码不一致');
            return false;
          }
          this.request.post('/user/register', this.registerUser).then((res) => {
            if (res.data.code === '200') {
              this.$message.success('注册成功');
              this.registerFormVisible = false;
              this.loginFormVisible = true;
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }
      });
    },
    logout() {
      sessionStorage.removeItem('user'); //只清空保持登录状态的缓存，记住密码的缓存不清空
      sessionStorage.setItem('islogin',false);//退出登录之后把登录字段设为false
      this.showlogin = true;
      this.showimg = false;
      if(this.$route.path!='/home'){
      this.$router.push('/home');//如果当前路由路径不是主页退出之后跳转到首页，保持无登录状态下只能访问首页
      }//不能随意跳转到主页，否则会有重定向冲突
      if(this.check==false){
      this.user.username='';//如果没有勾选记住密码则退出时把双向绑定到登录表单输入框的账号密码清空
      this.user.password='';}
      location.reload();//退出之后主动刷新页面来使得导航菜单项的选中状态（登录之后菜单项被选中会变黄）归零
      this.$message.success('退出成功');
    },
   }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>  
// less用来敲层级样式
.logo {
  position:absolute;
  height: 60px;
  width: 220px;
}

.logo img{
  height: 100%;
  width: 100%;
}

.userrtag{
  position: absolute;
    right: 20px;
    top:10px;
    cursor: pointer;
}

.link {
  text-decoration: none;
  color: cornflowerblue;
}

.el-menu-demo {
    //除logo和登录外的参数调整
    font-size: 100px;
    font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    font-weight: 1000;
    margin-top: 0px;
    margin-left: 250px;
    margin-bottom: 0px;
    .el-menu-item {
      width: 130px;
      height: 60px;
      text-align: center;
      background-color: #292c2f !important;
      margin-top: 0px;
    margin-bottom: 0px;
//   .el-menu--horizontal>.el-menu-item.is-active {
//     /* border-bottom: 2px solid #409EFF; */
//      background-color: #303133 !important;
//     color: #303133;
// }
    }
    
  }

.btn {
  width: 80px;
  align-items: center;
}
.header {
  position: relative;
  height: 60px;
  display: flex;
  background-color: #292c2f;
  color: #fff;
  .header-right {
    position: absolute;
    right: 20px;
    cursor: pointer;
  }
}

.dialog {
  background-color: rgba(255, 255, 255, 0);

  background-size: 100% 100%;
}
.dialog {
  .input {
    width: 100%;
  }
}
.register {
  text-align: right;
  .registerJmp {
    color: dodgerblue;
    cursor: pointer;
  }
}
.rememberMe {
  text-align: left;
}

.form{
  position: absolute;
  left: 37%;
  top: 30%;
  width: 25%;
}
.name {
    text-align: center;
    font-weight: 700;
    font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    /* margin: 10px 0px; */
    position: relative;
    left: 8%;
    top: 20%;
    font-size: 28px;
  }
</style>
